<style lang="scss" scoped>
  @import '@/assets/css/variable';
  .manage{
    position: absolute;
    top: 0;
    bottom: $tabbar-height;
    width: 100%;
    background-color: $main-bgc;
    min-height: 100%;
    font-size: 1.2rem;
    overflow: auto;
    box-sizing: border-box;
    .list{
      padding-bottom: 1rem;
      .item{
        margin-top: 1rem;
        margin-left: 1rem;
        margin-right: 1rem;
        padding: 1rem;
        background-color: white;
        .flex1{
          display: flex;
          justify-content: space-between;
          align-items: center;
          color: #999;
        }
        .flex2{
          display: flex;
          .flex2-left{
            flex: 0 0 10rem;
            width: 10rem;
            height: 7.5rem;
            border-radius: 0.6rem;
            img{
              border-radius: 0.6rem;
              object-fit: cover;
            }
          }
          
          .flex2-right{
            .title{
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 2; /* 设置行数 */
              -webkit-box-orient:vertical;
              color: $color-subtitle;
              line-height: 1.2em;
            }
            .desc{
              span{
                color: #999;
              }
            }
          }
        }
        .flex3{
          display: flex;
          justify-content: flex-end;
          .btn{
            margin-left: 1rem;
          }
        }
      }
    }
  }
  .show{
    height: auto;
    background-color: white;
    position:relative;
    .close-icon{
      position: absolute;
      width: 2.4rem;
      height: 2.4rem;
      right: 0.7rem;
      top: 0.7rem;
      border-radius: 1.2rem;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 2;
    }
    .posterHtml{
      // display: flex;
      #coverImg{
        display: flex;
        width: 100%;
        max-height: 30rem;
        object-fit: cover;
      }
      .imgBox{
        width: 100%;
      }
      .content{
        padding: 1.2rem;
        display: flex;
        height: 14rem;
        justify-content: space-between;
        .desc{
          word-wrap: break-word;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          height: 100%;
          .line1{
            font-size: 2rem;
            font-weight: bold;
            color:#333;
            display: flex;
            align-items: center;
          }
          .line2{
            font-size: 2.2rem;
            font-weight: 900;
            color:#111;
            // overflow: hidden;
            // text-overflow: ellipsis;
            // display: -webkit-box;
            // -webkit-line-clamp:2; /* 设置行数 */
            // -webkit-box-orient:vertical;
          }
        }
      }
      .bottom-box{
        padding-bottom: 2rem;
        padding-left:1.2rem;
        padding-right:1.2rem;
      }
    }
  }
  .imgBox{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: rgba($color: #000000, $alpha: 0.98);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 3000;
    img{
      width:100%;
    }
    .tips{
      color:white
    }
    .close-icon{
      position: fixed;
      width: 2.4rem;
      height: 2.4rem;
      right: 0.7rem;
      top: 0.7rem;
      border-radius: 1.2rem;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 3002;
    }
  }
  .fix-bottom{
    box-sizing: border-box;
    padding-bottom: 2rem;
  }
</style>
<template>
  <div class="manage">
    <!-- <my-activity-tabs></my-activity-tabs> -->
    <van-pull-refresh v-model="loadingRefresh" @refresh="refreshEvent">
      <van-tabs v-model="active" @click="onClickTabs" sticky>
        <van-tab v-for="item in tabList" :key="item.id" :title="item.name">
            <van-list v-model="loading" :finished="finished" finished-text="没有更多了" offset="100" @load="getActivityPage">
              <div class="list">
                <div class="item" v-for="item in list" :key="item.id">
                  <div class="flex1">
                    <span>{{item.createtime}}</span>
                    <span v-if="item.status!=2">距离结束还有{{item.leaveDay}}天</span>
                    <span v-else>已结束</span>
                  </div>
                  <div class="flex2 margT-l">
                    <div class="flex2-left" @click="toShowView(item)">
                      <img :src="item.cover">
                    </div>
                    <div class="flex2-right margL-l">
                      <div class="title fs-14 t-bold" :style="{color:item.status==2?'#999':'#333'}">{{item.title}}</div>
                      <div class="desc margT-l"><span>浏览 {{item.browse_num}}</span><span class="margL-l">参与 {{item.join_num}}</span></div>
                    </div>
                  </div>
                  <div class="flex3">
                    <div class="btn"><van-button plain type="default" size="small" @click="showPopBtn(item)">分享</van-button></div>
                    <div class="btn"><van-button plain :type="item.status==2?'default':'danger'" size="small" @click="toApplyListView(item)">名单</van-button></div>
                    <div class="btn"><van-button round icon="ellipsis" type="default" size="small" @click="showActionBtn(item.id)"></van-button></div>
                  </div>
                </div>
                <!-- <div v-if="list.length > 0">
                  <div class="load-more color-l padding-all-m margB-l margT-l" v-if="finished==false" @click="getActivityPage">加载更多</div>
                  <div class="no-data color-l padding-all-m margT-l" v-else>已经到底了</div>
                </div> -->
              </div>
            </van-list>
        </van-tab>
      </van-tabs>
    </van-pull-refresh>
    <van-action-sheet
      v-model="showAction"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @select="onSelect"
    />
    <van-popup v-model="showPop" position="bottom" round>
      <div class="show">
          <span class="close-icon" :style="{backgroundColor:$store.getters.getMasterColor}" @click="showPop = false"><van-icon color="white" name="cross" /></span>
          <!-- 海报html元素 -->
          <!-- <div id="posterHtml" :style="{backgroundImage: 'url('+thisItem.cover+')'}" v-show="false"> -->
          <div id="posterHtml" class="posterHtml">
            <img id="coverImg" :src="thisItem.cover">
            <!-- <div id="imgBox"></div> -->
            <div class="content">
              <div class="desc">
                <div class="line1"><span>快来参加</span> <van-icon class="margL-m" name="fire" color="red"/></div>
                <div class="line2">{{thisItem.title}}</div>
              </div>
              <!-- 二维码 -->
              <!-- <div class="qrcode" id="qrcode" ref="qrcode"></div> -->
              <canvas class="qrcode" id="qrCode-canvas"></canvas>
            </div>
            <div class="margT-l bottom-box">
              <div class="fs-16 t-bold">{{thisItem.merchantname}}</div>
              <div class="color-m margT-m">本次活动{{thisItem.end_time}}结束</div>
            </div>
          </div>
          <div class="fix-bottom padding-lr">
            <van-button :color="$store.getters.getMasterColor" block @click="createPoster" :loading="createLoading">生成海报</van-button>
          </div>
      </div>
    </van-popup>
    <div class="imgBox" v-if="showImgPop">
      <img :src="createImg">
      <div class="tips margT-m fs-16">Tips:长按以上海报即可保存或转发</div>
      <span class="close-icon" :style="{backgroundColor:$store.getters.getMasterColor}" @click="showImgPop = false"><van-icon color="white" name="cross" /></span>
    </div>
    <div class="tabbar-height"></div>
  </div>
</template>

<script>
// @ is an alias to /src
import { Tab, Tabs, List, PullRefresh, Loading, Button, ActionSheet, Toast, Popup, Icon  } from 'vant';
// import myActivityTabs from "@/components/ActivityTabs.vue";
import QRCode from 'qrcode'
import html2canvas from 'html2canvas'
import {myMixins} from "@/assets/js/mixins.js"
export default {
  name: "Manage",
  mixins: [myMixins],
  components: {
    [PullRefresh.name]: PullRefresh,
    [List.name]: List,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Loading.name]: Loading,
    [Button.name]: Button,
    [ActionSheet.name]: ActionSheet,
    [Popup.name]: Popup,
    [Icon.name]: Icon
    // myActivityTabs
  },
  data() {
    return {
      createLoading:false,
      showImgPop: false,
      posterImg:'',
      code:'',
      showPop: false,
      showAction: false,
      actions: [
        { name: '编辑活动' },
        { name: '复制活动' },
        { name: '结束活动' },
        { name: '删除活动' }
      ],
      active: 0,
      loadingRefresh:false,
      mainColor: "#FF0000",
      tabList: [{
        id: 0,
        name: "全部",
      },{
        id: 1,
        name: "进行中"
      },{
        id: 2,
        name: "已结束"
      }],
      list: [],
      loading: false,
      finished: false,
      pageNo: 1,
      pageSize: 10,
      id:"",
      thisItem:{},
      createImg:''
    }
  },
  created () {
    const _this = this;
    // this.getCode()
  },
  mounted() {
    // document.title = '活动管理'
    this.toHome()
    if (process.env.NODE_ENV == 'production') { //线上环境
      this.openid = localStorage.getItem("OPENID") || "没获取到"
    }else{
      this.openid = this.$store.state.openid || localStorage.getItem("OPENID")
    }
    if(this.openid=='undefined'||!this.openid||this.openid==undefined){
      window.location.href = "https://www.umiyun.net/addons/youmi_activitys/public/mobile/index.html#/case"
      return
    }
    this.configItemShare()
    this.getActivityPage()
  },
  methods: {
    getBase64Image(img) {  
      var canvas = document.createElement("canvas");  
      canvas.width = img.width;  
      canvas.height = img.height;  
      var ctx = canvas.getContext("2d");  
      ctx.drawImage(img, 0, 0, img.width, img.height);  
      var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();  
      var dataURL = canvas.toDataURL("image/"+ext);  
      return dataURL;  
    },
    //将图片对象转化为画布，返回画布
    ImageToCanvas(image) {
      var canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      canvas.getContext("2d").drawImage(image, 0, 0);//0, 0参数画布上的坐标点，图片将会拷贝到这个地方
      document.getElementById("imgBox").appendChild(canvas)
      //return canvas;
    },
    createPoster() {
      // 生成海报
      const vm = this
      vm.createLoading = true
      const domObj = document.getElementById('posterHtml')
      html2canvas(domObj, {
        useCORS: true,
        allowTaint: true,
        logging: true,
        letterRendering: true,
        onclone(doc) {
          let e = doc.querySelector('#posterHtml')
          e.style.display = 'block'
        }
      }).then(function(canvas) {
        // 在微信里,可长按保存或转发
        // let url = canvas.toDataURL('image/png')
        // const a = document.createElement('a'); // 创建a标签
        // a.setAttribute('download', `${new Date().getTime()}.png`);// download属性
        // a.setAttribute('href', url);// href链接
        // a.click();// 自执行点击事件
        let url = canvas.toDataURL('image/png')
        vm.createImg = url
        vm.showImgPop = true
        vm.createLoading = false
      })
    },
    toShowView(item) {
      const _this = this;
      this.thisItem = item
      let href = `${location.protocol}//${location.hostname + '/addons/youmi_activitys/public/mobile/c/index.html'}#/caseShow/${this.thisItem.model||'applyActivity'}/activityShow/${this.thisItem.id}`;
      window.location.href = href;
    },
    createQrcode(){
      let href = `${location.protocol}//${location.hostname + '/addons/youmi_activitys/public/mobile/c/index.html'}#/caseShow/${this.thisItem.model||'applyActivity'}/activityShow/${this.thisItem.id}`;
      let canvas = document.getElementById('qrCode-canvas')
      QRCode.toCanvas(canvas, href, (error) => {
        if (error) {
          console.log(error)
        } else {
          canvas.style.width = '12rem'
          canvas.style.height = '12rem'
        }
      })
    },
    toApplyListView(item) {
      this.$store.commit('setActivityItem',item)
      this.$router.push(`/manage/applyList`)
    },
    showPopBtn(item) {
      const _this = this;
      this.showPop = true
      this.thisItem = item
      console.log(this.thisItem,"thisItem")
      
      _this.$nextTick(function () {
			    _this.createQrcode()
			})
      
      // let img = document.getElementById('coverImg');
      // this.ImageToCanvas(img)
      // this.thisItem.cover = this.getBase64Image(img)
      // this.$forceUpdate()
    },
    showActionBtn(id) {
      this.id = id
      this.showAction = true
    },
    onSelect(item) {
      // 默认情况下点击选项时不会自动收起
      // 可以通过 close-on-click-action 属性开启自动收起
      // this.show = false;
      console.log(item.name);
      if(item.name=="编辑活动"){
        this.$router.push(`/case/applyActivity/${this.id}?is_edit=1`)
      }else if(item.name=="复制活动"){
        this.$router.push(`/case/applyActivity/${this.id}?is_edit=0`)
      }else if(item.name=="删除活动"){
        this.activityDel()
      }else if(item.name=="结束活动"){
        this.activitySave()
      }
    },
    activitySave() {
      const _this = this;
      let params = {
        id: _this.id,
        status: 1,
      }
      // params.cover = this.cover
      this.$request.activitySave(params).then(res=>{
        console.log("res", res)
        if(res.ret == 200){
          Toast("结束成功")
          _this.list = []
          _this.pageNo = 1
          _this.getActivityPage()
        }
      })
    },
    refreshEvent() {
      this.pageNo = 1;
      this.list = [];
      this.getActivityPage()
    },
    onLoad() {
      console.log("onLoad")
    },
    activityDel(){
      const _this = this;
      let params = {
        id:this.id
      }
      const toast = Toast.loading({
          forbidClick: true,
          message: '加载中...',
      });
      _this.$request.activityDel(params).then(res=>{
        Toast("删除成功")
        _this.list = []
        _this.pageNo = 1
        _this.getActivityPage()
      }).finally(()=>{
        toast.clear()
      })
    },
    getActivityPage() {
      const _this = this;
      let params = {
        openid: _this.openid, // _this.$store.state.openid
        status: _this.active,
        pageNo: _this.pageNo,
        pageSize: _this.pageSize
      }
      this.loading = true
      this.loadingRefresh = true
      console.log(params,"params")
      _this.$request.getActivityPage(params).then(res=>{
        let data = res.data.data
        const list = data.map(item => {
          const leaveTime = new Date(item.end_time).getTime() - new Date().getTime()
          const leaveDay = leaveTime/1000/86400
          item.leaveDay = Math.floor(leaveDay)
          return item
        })
        _this.list.push(...list)
        
        if(_this.pageNo >= (Math.ceil(res.data.totalCount/_this.pageSize))){
          _this.finished = true;
        }else{
          _this.pageNo++
        }
        // this.$store.commit('setCaseList', this.caseList);
      }).finally(()=>{
        console.log('finally')
        this.loadingRefresh = false;
        this.loading = false;
      })
    },
    onClickTabs(index) {
      console.log("onClickTabs", index)
      this.active = index
      this.list = []
      this.pageNo = 1
      this.getActivityPage()
      if(index== 0) {
        //全部
      }else if(index == 1) {
        //进行中
      }else if(index == 2) {
        //已结束
      }
      // this.caseList = this.$store.getters.getCaseList
      // this.$emit("tabClick", index)
      // 请求接口获取对应的caseList
    }
  }
};
</script>
